<template>
    <div class="contianer">

        <div class="baseMess">
            <div class="userMess">
                <div class="userHeadImg">
                    <el-avatar shape="square" :size="130" :src="userMess.avatar ? userMess.avatar : circleUrl"></el-avatar>
                </div>
                <div class="mess">
                    <span style="font-family:Verdana,'楷体';">{{ userMess.nickName }}</span><br>
                    <span style="font-family:Verdana,'楷体';line-height: 25px;">姓名:{{ userMess.userName }}</span><br>
                    <span style="font-family:Verdana,'楷体';line-height: 25px;">性别:{{ userMess.sex == 0 ? '男' : '女'
                    }}</span><br>
                    <span style="font-family:Verdana,'楷体';line-height: 25px;">邮箱:{{ userMess.email }}</span><br>
                    <span style="font-family:Verdana,'楷体';line-height: 25 px;">手机:{{ userMess.phone }}</span><br>
                </div>


            </div>

            <div class="menu">
                <el-tabs v-model="activeName" @tab-click="handleClick">
                    <el-tab-pane label="基本信息" name="first">
                        <div class="menuLeft">
                            <el-upload class="avatar-uploader" action="api/util/uploadImg" name="imgFile" 
                                :show-file-list="false" :on-success="handleAvatarSuccess"
                                :before-upload="beforeAvatarUpload" :disabled="!messChange" disabled="">
                                <img v-if="userChangeMess.avatar" :src="userChangeMess.avatar" class="avatar">
                                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                            </el-upload>
                            <div>
                                <el-button type="primary" class="uploadButton" @click="uploadButton"
                                    v-if="messChange">点击上传头像<i class="el-icon-upload el-icon--right"></i></el-button>
                            </div>
                        </div>
                        <div class="menuRigth">
                            <el-form :model="userChangeMess" :rules="rules" ref="userChangeMess" label-width="100px"
                                size="mini" class="demo-ruleForm">
                                <el-form-item label="姓名：" size="mini">
                                    <el-input v-if="messChange" v-model="userChangeMess.userName"
                                        class="menuUserName"></el-input>
                                    <span v-else class="menuUserName">{{ userChangeMess.userName }}</span>
                                    <div class="navbar">
                                        <el-button @click="messchange" type="primary" icon="el-icon-edit"
                                            :style="changeDisplay ? display1 : display0" circle></el-button>
                                        <ul :style="messChange ? width1 : width0">
                                            <el-button type="info" icon="el-icon-close" @click="cancellation"
                                                circle></el-button>
                                            <el-button type="danger" icon="el-icon-check" @click="confirmChange"
                                                circle></el-button>
                                        </ul>
                                    </div>
                                </el-form-item>
                                <el-form-item label="昵称：" prop="name">
                                    <el-input v-model="userChangeMess.nickName" class="menuNickName" maxlength="8"
                                        v-if="messChange" show-word-limit clearable></el-input>
                                    <span v-else>{{ userChangeMess.nickName }}</span>
                                </el-form-item>

                                <el-form-item label="性别：" prop="resource">
                                    <el-radio-group v-if="messChange" v-model="userChangeMess.sex">
                                        <el-radio label="0">男&nbsp;&nbsp;&nbsp;</el-radio>
                                        <el-radio label="1">女</el-radio>
                                    </el-radio-group>
                                    <span v-else>
                                        <span v-if="userChangeMess.sex == 0">男</span>
                                        <span v-if="userChangeMess.sex == 1">女</span>
                                    </span>

                                </el-form-item>
                                <el-form-item label="手机：">
                                    <el-input v-if="messChange" v-model="userChangeMess.phone"></el-input>
                                    <span v-else>{{ userChangeMess.phone }}</span>
                                </el-form-item>
                                <el-form-item label="邮箱：">
                                    <el-input v-if="messChange" v-model="userChangeMess.email"></el-input>
                                    <span v-else>{{ userChangeMess.email }}</span>
                                </el-form-item>
                            </el-form>
                        </div>

                    </el-tab-pane>
                    <el-tab-pane label="点赞文章" name="second" class="paneDiv">
                        <el-empty v-if="tableDataSecond == ''" description="没有点赞文章"></el-empty>
                        <div class="oneArtcle" v-for="articleData in tableDataSecond">
                            <img class="articleImg" v-if="articleData.fileUid" :src="articleData.fileUid" alt="加载失败"
                                @click="oneArticle(articleData)">
                            <div class="articleMess" @click="oneArticle(articleData)">
                                <p class="titleList" v-html="articleData.title" @click="oneArticle(articleData)"></p>

                                <p class="summary" v-html="articleData.summary" @click="oneArticle(articleData)"></p>
                                <div class="articleMessData" @click="oneArticle(articleData)">
                                    <div class="createdTime">
                                        <p>发布时间</p>
                                        <p v-html="articleData.createdTime"></p>
                                    </div>
                                    <div class="clickCount">
                                        <p v-html="articleData.clickCount"></p>
                                        <p>阅读</p>
                                    </div>
                                    <div class="clickCount">
                                        <p v-html="articleData.likeCount"></p>
                                        <p>点赞</p>
                                    </div>
                                    <div class="collectCount">
                                        <p v-html="articleData.collectCount"></p>
                                        <p>收藏</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </el-tab-pane>
                    <el-tab-pane label="收藏文章" name="third" class="paneDiv">
                        <el-empty v-if="tableDataThird == ''" description="没有收藏文章"></el-empty>
                        <div class="oneArtcle" v-for="articleData in tableDataThird">

                            <img class="articleImg" v-if="articleData.fileUid" :src="articleData.fileUid" alt="加载失败"
                                @click="oneArticle(articleData)">
                            <div class="articleMess" @click="oneArticle(articleData)">
                                <p class="titleList" v-html="articleData.title" @click="oneArticle(articleData)"></p>

                                <p class="summary" v-html="articleData.summary" @click="oneArticle(articleData)"></p>
                                <div class="articleMessData" @click="oneArticle(articleData)">
                                    <div class="createdTime">
                                        <p>发布时间</p>
                                        <p v-html="articleData.createdTime"></p>
                                    </div>
                                    <div class="clickCount">
                                        <p v-html="articleData.clickCount"></p>
                                        <p>阅读</p>
                                    </div>
                                    <div class="clickCount">
                                        <p v-html="articleData.likeCount"></p>
                                        <p>点赞</p>
                                    </div>
                                    <div class="collectCount">
                                        <p v-html="articleData.collectCount"></p>
                                        <p>收藏</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </el-tab-pane>
                    <el-tab-pane label="最近浏览" name="fourth" class="paneDiv">
                        <el-empty v-if="tableDataFourth == ''" description="没有最近文章"></el-empty>
                        <div class="oneArtcle" v-for="articleData in tableDataFourth">
                            <img class="articleImg" v-if="articleData.fileUid" :src="articleData.fileUid" alt="加载失败"
                                @click="oneArticle(articleData)">
                            <div class="articleMess" @click="oneArticle(articleData)">
                                <p class="titleList" v-html="articleData.title" @click="oneArticle(articleData)"></p>

                                <p class="summary" v-html="articleData.summary" @click="oneArticle(articleData)"></p>
                                <div class="articleMessData" @click="oneArticle(articleData)">
                                    <div class="createdTime">
                                        <p>发布时间</p>
                                        <p v-html="articleData.createdTime"></p>
                                    </div>
                                    <div class="clickCount">
                                        <p v-html="articleData.clickCount"></p>
                                        <p>阅读</p>
                                    </div>
                                    <div class="clickCount">
                                        <p v-html="articleData.likeCount"></p>
                                        <p>点赞</p>
                                    </div>
                                    <div class="collectCount">
                                        <p v-html="articleData.collectCount"></p>
                                        <p>收藏</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </el-tab-pane>
                </el-tabs>
            </div>

        </div>


        <!-- 弹出的页面内容 -->
        <el-dialog :visible.sync="uploadHeadImg" :width="'800px'">
            <div slot="title" class="header-title">
                <span class="title-name">
                    <i class="el-icon-edit" style="margin-right:10px"></i>
                </span>
                <span class="title-age">头像修改</span>
            </div>
            <div class="cropper-component">
                <!-- 工具箱部分 -->
                <div class="btn-box">

                    <div class="scope-btn">
                        <label class="btn" for="uploads"><i class="el-icon-download"></i>选择头像</label>
                        <input type="file" id="uploads" style="position:absolute; clip:rect(0 0 0 0);"
                            accept="image/png, image/jpeg, image/gif, image/jpg, image/png"
                            @change="uploadImg($event, 'blob', 1)">
                        <el-button plain icon="el-icon-zoom-in" @click="changeScale(1)" type="info"
                            class="imgUtils">放大</el-button>
                        <el-button type="info" plain icon="el-icon-zoom-out" @click="changeScale(-1)"
                            class="imgUtils">缩小</el-button>
                        <el-button type="info" plain @click="rotateLeft" class="imgUtils"><i
                                class="el-icon-refresh-left"></i>左旋转</el-button>
                        <el-button type="info" plain @click="rotateRight" class="imgUtils"><i
                                class="el-icon-refresh-right"></i>右旋转</el-button>
                        <el-button type="danger" @click="upload()" class="imgUtils" style="width: 100px;">确认上传&nbsp;<i
                                class="el-icon-upload el-icon--right"></i></el-button>
                    </div>
                </div>
                <!-- 展示内容部分 -->
                <div class="show_box">
                    <!-- 展示选中图片 -->
                    <div class="cropper" :style="{ width: setWidth / 2 + 'px', height: setHeight / 2 + 'px' }">
                        <vueCropper ref="cropper" :img="option.img" :outputSize="option.size"
                            :outputType="option.outputType" :info="option.info" :full="option.full"
                            :canMove="option.canMove" :canMoveBox="option.canMoveBox" :original="option.original"
                            :autoCrop="option.autoCrop" :autoCropWidth="option.autoCropWidth"
                            :autoCropHeight="option.autoCropHeight" :enlarge="option.enlarge" :fixedBox="option.fixedBox"
                            @realTime="realTime"></vueCropper>
                    </div>
                    <!-- 展示缩略图 -->
                    <div class="preview-box">
                        <div class="preview">
                            <img :src="previews.url ? previews.url : circleUrl"
                                :style="previews.url ? previews.img : 'width:130px;height:140px'" />
                        </div>
                        <div style="margin-left: 40px;">
                            <span style="left: 50px;">头像预览</span>
                        </div>
                    </div>
                </div>

            </div>
            <div>
                <span style="color: red;">*</span>
                <span>&nbsp;仅支持jpg,npg,jpeg格式的图片上传，图片大小不超10MB</span>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import { $FindMyAccountMess } from '@/assets/api/user.js'
import { ChangeMyMess } from '@/assets/api/user.js'
import { UploadImg } from '@/assets/api/user.js'
import { findMyLickArticle } from '@/assets/api/user.js'
import { findMyCollectArticle } from '@/assets/api/user.js'
import { findMyLookArticle } from '@/assets/api/user.js'

export default {
    props: {
        setWidth: {
            type: Number,
            default: 400
        },
        setHeight: {
            type: Number,
            default: 400
        }
    },
    data() {
        return {
            tableDataSecond: '',
            tableDataThird: '',
            tableDataFourth: '',
            

            //剪切图片上传
            crap: false,
            previews: {},
            option: {
                img: '', // 裁剪图片的地址
                info: false, // 裁剪框的大小信息
                outputSize: 1, // 剪切后的图片质量（0.1-1）
                outputType: 'jpg', // 裁剪生成的图片的格式
                canMove: true,  // 上传图片是否可以移动
                original: false,  // 上传图片是否显示原始宽高
                canMoveBox: true,  // 截图框能否拖动
                autoCrop: true, // 是否默认生成截图框
                autoCropWidth: this.setWidth / 3,
                autoCropHeight: this.setHeight / 3,
                fixedBox: true, // 截图框固定大小
                fixed: false, //是否开启截图框宽高固定比例
                enlarge: 3,//图片根据截图框输出比例倍数

            },
            fileName: '',  // 本机文件地址
            downImg: '#',
            imgFile: '',
            uploadImgRelaPath: '', // 上传后的图片的地址（不带服务器域名）

            activeName: 'first',
            circleUrl: "https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png",
            userMess: {},
            uploadHeadImg: false,
            messChange: false,
            changeDisplay: false,
            width0: 'width:0px',
            width1: 'width:90px',
            display0: '',
            display1: 'display:none',
            userChangeMess: {},
            avatar: '',
            rules: {
                name: [
                    { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
                ],

            },

        }
    },
    created() {
        this.init();
    },
    methods: {
        //点击查看文章详情  
        oneArticle(articleData) {
            sessionStorage.setItem("id", JSON.stringify(articleData.id));
            this.$router.push({
                name: 'oneArticle'
            });
        },
        
        handleClick(tab, event) {
            if (tab.name == 'second') {
                this.findArticleSecond();
            } else if (tab.name == 'third') {
                this.findArticleThird();
            } else if (tab.name == 'fourth') {
                this.findArticleFourth();
            }
        },

        //查询点赞文章
        findArticleSecond() {
            findMyLickArticle(this.userMess.id).then((res) => {
                if (res.data.success) {
                    this.tableDataSecond = res.data.data.findLikeArticleById;
                } else {
                    this.message(res);
                }
            }).catch((err) =>{
               console.log(err);
            })
        },
        //查询收藏文章
        findArticleThird() {
            findMyCollectArticle(this.userMess.id).then((res) => {
                if (res.data.success) {
                    this.tableDataThird = res.data.data.findCollectArticleById;
                } else {
                    this.message(res);
                }
            }).catch((err) =>{
                console.log(err);
            })
        },
        //查询最近浏览文章
        findArticleFourth() {
            findMyLookArticle(this.userMess.id).then((res) => {
                if (res.data.success) {
                    this.tableDataFourth = res.data.data.findLookArticleById;
                }  else {
                    this.message(res);
                }
            }).catch((err) =>{
                console.log(err);
            })
        },
        uploadButton() {
            this.uploadHeadImg = true;
        },
        messchange() {
            this.messChange = true;
            this.changeDisplay = true;
        },
        cancellation() {
            this.userChangeMess = JSON.parse(JSON.stringify(this.userMess));
            this.messChange = false;
            setTimeout(() => {
                this.changeDisplay = false;
            }, 500);

        },
        confirmChange() {
            ChangeMyMess(this.userChangeMess).then((res) => {
                console.log(res);
                if (res.data.success) {
                    this.$message({
                        message: '修改成功',
                        type: 'success'
                    })
                    this.userMess = JSON.parse(JSON.stringify(this.userChangeMess));//修改值之后进行深拷贝会显
                    this.messChange = false;

                    setTimeout(() => {
                        this.changeDisplay = false;
                    }, 500);
                    location.reload();
                    //this.userMess = res.data.data;
                } else {
                    this.$message({
                        message: res.data.message,
                        type: 'error'
                    })
                }
            }).catch((err) => {

            })

        },
        init() {
            $FindMyAccountMess().then(res => {
                if (res.data.success) {
                    this.userMess = res.data.data.findMyAccountMess;
                    this.userChangeMess = JSON.parse(JSON.stringify(this.userMess));
                }
            }).catch(err => {
                console.log(err);
            })
        },
        //图片上传
        handleAvatarSuccess(res) {
            if (res.success) {
                this.userChangeMess.avatar = res.data.resPath
                this.$message({
                    type: 'success',
                    message: ""
                })
            } else {
                this.$message({
                    type: 'error'
                })
            }
        },
        beforeAvatarUpload(file) {
            const isJPG = (file.type === 'image/jpg' || file.type === 'image/jpeg' || file.type === 'image/png');
            const isLt2M = file.size / 1024 / 1024 < 4;
            if (!isJPG) {
                this.$message.error('上传头像图片只能是 JPG和PNG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 4MB!');
            }
            return isJPG && isLt2M;
        },
        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    alert('submit!');
                } else {
                    return false;
                }
            });
        },
        resetForm(formName) {
            this.$refs[formName].resetFields();
        },

        // 放大/缩小
        changeScale(num) {
            num = num || 1;
            this.$refs.cropper.changeScale(num);
        },
        // 坐旋转
        rotateLeft() {
            this.$refs.cropper.rotateLeft();
        },
        // 右旋转
        rotateRight() {
            this.$refs.cropper.rotateRight();
        },
        // 上传图片（点击上传按钮）
        finish(type) {
            let formData = new FormData();
            // 输出
            if (type === 'blob') {
                this.$refs.cropper.getCropBlob((data) => {
                    let img = window.URL.createObjectURL(data);
                    formData.append('file', data, 'da.jpg');
                    this.$emit('postFile', formData);
                })
            } else {
                this.$refs.cropper.getCropData((data) => {
                    formData.append('images', data);
                    this.$emit('postFile', formData);
                })
            }
        },
        // 实时预览函数
        realTime(data) {
            this.previews = data;
        },

        // 上传图片到服务器
        upload() {
            var aLink = document.createElement('a');
            let timer = new Date().getTime()
            aLink.download = timer;//文件名
            // 获取截图的blob数据
            this.$refs.cropper.getCropBlob((data) => {
                let file = new window.File([data], this.fileName, { type: 'image/jpeg,image/png' })
                var formData = new FormData();
                formData.append('imgFile', file);

                UploadImg(formData).then((res) => {
                    console.log(res);
                    if (res.data.success) {
                        this.userChangeMess.avatar = res.data.data.resPath;
                        this.uploadHeadImg = false;
                        this.$message({
                            message: "图片上传成功",
                            type: 'success',
                        })
                    } else {
                        this.$message({
                            message: "图片上传成功失败，请检查网络",
                            type: 'error',
                        })
                    }
                }).catch((err) =>{

                })
            })
        },

        // 选择本地图片
        uploadImg(e, type, num) {//num代表第几个
            // 上传图片
            var file = e.target.files[0];
            this.fileName = file.name;
            if (!/\.(jpg|png)$/.test(e.target.value)) {
                this.$message.info('证件照图片必须是jpg格式');
                return false;
            }
            let reader = new FileReader();
            reader.onload = (e) => {
                let data = '';//生成图片地址
                if (typeof e.target.result === 'object') {
                    if (type == 'blob') {
                        // 把Array Buffer转化为blob 如果是base64不需要
                        data = window.URL.createObjectURL(new Blob([e.target.result]));
                    }
                }
                else {
                    data = e.target.result;
                }
                if (num === 1) {
                    this.option.img = data;
                }
            }
            if (type == 'blob') {
                // 转化为blob
                reader.readAsArrayBuffer(file);
            } else {
                // 转化为base64
                reader.readAsDataURL(file);
            }
        },

    }
}
</script>

<style scoped>
* {
    font-family: "Hiragino Sans GB"
}

* {
    margin: 0;
    padding: 0;
}


.paneDiv {
    margin-top: 20px;
    overflow-y: scroll;
    height: 280px;
}


.articleMessData p {
    float: left;
    margin-right: 25px;
    font-size: 10px;
    position: relative;
    top: -30px;
    user-select: none;
}

.articleMessData p:nth-child(1) {
    float: left;
    margin-right: 5px;
    font-size: 10px;
    position: relative;
    top: -30px;
}

.articleMessData {
    height: 0px;
}

.summary {
    height: 80px;
    font-size: 12px;
    /*弹性伸缩盒子*/
    display: -webkit-box;
    /*垂直排列*/
    -webkit-box-orient: vertical;
    /*只显示3行*/
    line-clamp: 3;
    -webkit-line-clamp: 3;
    /*溢出隐藏*/
    overflow: hidden;
    /*省略号代替*/
    text-overflow: ellipsis;
    position: relative;
    top: -15px;
    user-select: none;
}

.font-family {}

.imgUtils {
    width: 80px;
    height: 30px;
}


.titleList {
    line-height: 40px;
    color: black;
    height: 40px;
    position: relative;
    top: -10px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    user-select: none;
}


.oneArtcle {

    min-width: 900px;
    width: 900px;
    margin: 0 auto;
    height: 120px;
    margin-bottom: 10px;
    border-bottom: solid 1px #cccccc;
    border-right: solid 1px #cccccc;
    border-top: solid 1px #e3e2e2;
    border-left: solid 1px #e3e2e2;
    padding: 5px;
}


.articleImg {

    background-color: white;
    float: left;
    width: 110px;
    height: 110px;
    margin: 5px;

}

.articleMess {
    float: left;

    width: 75%;
    height: 110px;
    margin: 5px;
}

.cropper-component {
    width: 800px;
    height: 350px;
    margin: 0 auto;
    position: relative;

    .btn-box {
        margin: 20px 0;
        margin-left: 100px;


        .btn {
            outline: none;
            display: inline-block;
            line-height: 1;
            white-space: nowrap;
            cursor: pointer;
            text-align: center;
            -webkit-box-sizing: border-box;
            box-sizing: border-box;
            outline: 0;
            -webkit-transition: .1s;
            transition: .1s;
            font-weight: 500;
            padding: 8px 15px;
            font-size: 14px;
            border-radius: 3px;
            color: #fff;
            background-color: #409EFF;
            border-color: #409EFF;
            margin-right: 10px;
            height: 28px;

        }
    }

    .show_box {
        display: flex;
        position: absolute;
        left: 70px;
        top: 80px;


        .cropper {
            margin-left: 50px;
        }

        .preview-box {
            margin-left: 170px;
            top: 60px;
            left: 10px;

            .preview {
                width: 130px;
                height: 135px;
                border: 1px solid #ccc;
                background-color: #ccc;
                margin: 5px;
                overflow: hidden;
            }
        }
    }

}

.uploadHeadImg {
    border: solid 1px red;

    height: 400px;
}

.uploadButton {
    margin: 30px;
    width: 130px;
    height: 35px;
}

body {
    height: 100vh;
    /* 背景渐变 */
    background: linear-gradient(200deg, #ddd6f3, #faaca8);
}

/* 三个元素都需要弹性布局，所以写在一块 */
body,
.navbar,
.navbar ul {
    display: flex;
    justify-content: center;
    align-items: center;
}

.navbar {
    position: absolute;
    left: 160px;
    bottom: 15px;
    justify-content: center;
    align-items: center;
    height: 0px;
}


.navbar ul {
    /* 溢出隐藏 */
    overflow: hidden;
    /* 在这里加个过渡，可以让展开和收起自然一些 */
    transition: all 0.5s;
    /* 让文字不换行显示 */
    white-space: nowrap;
}

.navbar ul li {
    list-style: none;
    margin: 0px 15px;
}



.demo-ruleForm {
    width: 500px;
}

.menuNickName {
    width: 50%;
    margin-right: 30px;
    display: inline-block;
}

.menuUserName {
    width: 40%;
    margin-right: 30px;
    display: inline-block;
}

.menuRigth el-input {
    display: inline;
}

.menuLeft {
    float: left;
}

.menuRigth {
    margin: 10px;
    margin-left: 30px;
    float: left;
}

.avatar {
    height: 200px;

}

.avatar-uploader {
    height: 200px;
    width: 200px;

}

.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}



.userHeadImg {
    position: relative;
    top: 40px;
    left: 40px;
}

.mess {
    position: relative;
    top: -90px;
    left: 200px;
    width: 700px;
    height: 130px;
}

.mess span {
    margin-top: 240px;
    color: #676565;

}

.mess span:first-child {
    font-size: 30px;
    color: #676565;

}


.menu {
    padding: 20px
}

.userMess {
    height: 200px;
}

.contianer {
    height: auto;
}

.baseMess {

    border: solid 1px #cccccc;
    width: 1000px;
    height: 600px;
    margin: 0 auto;
    margin-top: 30px;
    border-radius: 20px
}
</style>